package cn.webrx.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@WebListener
public class OnlineCounter implements HttpSessionListener, HttpSessionAttributeListener, ServletRequestListener {
    public static Map<String, Integer> online = new HashMap<>();
    public static Set<String> mems = new HashSet<>();

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        //event.getSession().setAttribute("member","admin");
        //HttpSessionAttributeListener.super.attributeAdded(event);

        //member
        System.out.println(event.getName());
        //value
        System.out.println(event.getValue());
        if("member".equalsIgnoreCase(event.getName())){
            mems.add(event.getValue().toString());
        }

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {

        if("member".equalsIgnoreCase(event.getName())){
            mems.remove(event.getValue().toString());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        HttpSessionAttributeListener.super.attributeReplaced(event);
    }

    HttpServletRequest request;

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        request = (HttpServletRequest) sre.getServletRequest();
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        ServletContext application = session.getServletContext();
        online.put(request.getRemoteAddr(), 1);
        System.out.println("上线" + request.getRemoteAddr());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        online.remove(request.getRemoteAddr());
        System.out.println("下线");
    }
}
